package com.guxingke.gblog.controller.back;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.guxingke.gblog.controller.BaseController;
import com.guxingke.gblog.dmo.Category;

@Controller
@RequestMapping("/manage/category")
public class CategoryManageController extends BaseController {

	@RequestMapping
	public ModelAndView list() {
		ModelAndView mav = new ModelAndView();

		mav.addObject("mainPage", "category/manage-list.jsp");

		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/edit")
	public ModelAndView edit(
			@RequestParam(value = "categoryId", required = true) Integer id) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("category", categoryService.getCategory(id));

		mav.addObject("mainPage", "category/manage-save.jsp");

		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/new")
	public ModelAndView save() {
		ModelAndView mav = new ModelAndView();

		mav.addObject("mainPage", "category/manage-save.jsp");

		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/delete")
	public String delete(
			@RequestParam(value = "categoryId", required = true) Integer id,
			HttpServletRequest request, HttpSession session) {

		if (categoryService.exist(id)) {
			request.setAttribute("error", "此类别下尚有文章，不能删除");
			return "forward:/manage/category.do";
		}
		categoryService.deleteCategory(id);
		// 更新session缓存
		session.setAttribute("categories", categoryService.getCategories());

		return "redirect:/manage/category.do";
	}

	@RequestMapping("/save")
	public String save(Category category, HttpSession session) {
		// update
		if (category.getId() != null) {
			categoryService.updateCategory(category);
		} else {
			// new category
			categoryService.saveCategory(category);
		}

		// 更新session缓存
		session.setAttribute("categories", categoryService.getCategories());

		return "redirect:/manage/category.do";
	}
}
